<?php

namespace app\service;

use app\model\User;
use GuzzleHttp\Client;
use Tinywan\Jwt\JwtToken;
use app\enum\UserCode;

class UserService extends Base
{
    //登录
    public function toLoginByCode($code, $platform, $nickname, $avatar): array
    {


        //获取微信小程序的openid
        switch ($platform) {
            case UserCode::PLATFORM['测试']:
                $openid = $code;
                break;
            case UserCode::PLATFORM['微信']:
                $openid = $this->get_wx_openid($code);
                break;
            case UserCode::PLATFORM['抖音']:
                $openid = $this->get_dy_openid($code);
                break;
            default:
                return apiError('平台错误');
        }
        //查询会员信息
        $userInfo = User::where(['openid' => $openid])->find();
        if (empty($userInfo)) {
            //注册
            $param = [
                'openid' => $openid,
                'nickname' => $nickname,
                'avatar' => $avatar,
                'platform' => $platform,
                'join_ip' => request()->getRemoteIp(),
                'join_time' => date('Y-m-d H:i:s'),
                'status' => UserCode::STATUS_NORMAL,
            ];
            $id = User::insertGetId($param);
            if (!$id) {
                return apiError('注册失败');
            }
            //注册成功
            $userInfo = User::where(['id' => $id])->find();
        }
        if ($userInfo['status'] == UserCode::STATUS_DISABLE) {
            return apiError('该账号已停用');
        }

        $userInfo->last_time = date('Y-m-d H:i:s');
        $userInfo->last_ip = request()->getRemoteIp();
        $userInfo->save();

        $extend = [
            'id' => $userInfo['id'],
            'name' => '模版',
            'access_exp' => 8640000,  // 100天
            'refresh_exp' => 8640000,  // 100天
            'client' => JwtToken::TOKEN_CLIENT_MOBILE
        ];
        $generateToken = JwtToken::generateToken($extend);

        if ($generateToken) {
            $data = ['token' => $generateToken['access_token'], 'user_info' => $userInfo];
            return apiSuccess($data);
        }
        return apiError('失败');

    }


    //获取微信小程序的openid
    protected function get_wx_openid($js_code)
    {
        $appid = env('WECHAT_APPID', '');
        $secret = env('WECHAT_SECRET', '');
        //改成
        //创建一个有基本URI的客户端
        $client = new Client();
        //发送请求
        $response = $client->request('GET', 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $secret . '&js_code=' . $js_code . '&grant_type=authorization_code');
        //获取返回数据
        $data = json_decode($response->getBody(), true);
        if (isset($data['openid'])) {
            return $data['openid'];
        }
        return $response;
    }


    //获取抖音的openid
    protected function get_dy_openid($code)
    {
        $appid = env('DOUYIN_APPID', '');
        $secret = env('DOUYIN_SECRET', '');

        //创建一个有基本URI的客户端
        $client = new Client();
        //发送请求
        $response = $client->request('GET', 'https://minigame.zijieapi.com/mgplatform/api/apps/jscode2session?appid=' . $appid . '&secret=' . $secret . '&code=' . $code);
        //获取返回数据
        $data = json_decode($response->getBody(), true);
        if (isset($data['openid'])) {
            return $data['openid'];
        }
        return $response;
    }


}